package com.xiaobawang.knowledge.spider.filter;

import org.slf4j.MDC;

import jakarta.servlet.*;
import java.io.IOException;
import java.util.UUID;

/**
 * @description tracId 生成
 * @author 18101119
 * @date 2024/3/25 14:05
 * @email songxinhang2023@e-chinalife.com
 * @id 18101119
 * @phone 13001321080
 */
public class TraceIdFilter implements Filter {

    /**
     * @author synhard
     * @id 18101119
     * @description 请求过滤器，请求携带 traceId
     * @date 2024/3/25 17:10
     * @param request 请求
     * @param response 响应
     * @param chain 请求链
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        try {
            // 在MDC中设置traceId
            MDC.put("traceId", UUID.randomUUID().toString());
            chain.doFilter(request, response);
        } finally {
            // 确保最后清除traceId，避免内存泄漏
            MDC.remove("traceId");
        }
    }
}